#!/bin/bash

CA_HOME=CA

init()
{
	mkdir $CA_HOME

	cd $CA_HOME
	mkdir newcerts private conf certs

	touch index.txt
	echo "01" > serial
	echo "00" > crlnumber

	cat > conf/gen_ca.conf << EOF
[ req ]
default_keyfile = private/cakey.pem
default_md = sha256
prompt = no
distinguished_name = ca_distinguished_name
x509_extensions = ca_extentions

[ ca_distinguished_name ]
# 国家，可不填
countryName 	        = CN
# 省，可不填
#stateOrProvinceName    = JiangSu
# 市，可不填
#localityName           = NanJing
# 组织/公司名，可不填
organizationName       = SelfSign org
# 部门名，可不填
organizationalUnitName = SelfSign CA
# 必填，常用名
commonName             = SelfSign Root CA


[ ca_extentions ]
basicConstraints=CA:true,pathlen:3
EOF

	cat > conf/ca.conf << EOF
[ ca ]
default_ca = selfca

[ selfca ]
dir            = ./
database       = \$dir/index.txt
certs          = \$dir/certs
new_certs_dir  = \$dir/newcerts

crl_dir        = \$dir/crl
crlnumber      = \$dir/crlnumber
crl            = \$dir/crl.pem 

certificate    = \$dir/cacert.pem
serial         = \$dir/serial
private_key    = \$dir/private/cakey.pem
RANDFILE       = \$dir/private/.rand

default_days   = 365
default_crl_days= 30
default_md     = sha256
unique_subject = no
# 请求匹配策略
policy         = policy_anything

[ policy_anything ]
countryName             = optional
stateOrProvinceName     = optional
localityName            = optional
organizationName        = optional
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional
EOF

	cd -
}


genca()
{
	cd $CA_HOME
	# 生成根密钥
	openssl genrsa -out private/cakey.pem 2048

	# 生成根证书，10年有效期，可修改
	openssl req -new -x509 -key private/cakey.pem -out cacert.pem -config conf/gen_ca.conf -days 3650
}


help()
{
	echo "Usage: $0 function"
	echo "functions:"
	echo "     init"
	echo "     genca"
	echo "     help"
}


if [ $# -lt 1 ]; then
	help
	exit 0
fi

func=$1

$func


